package com.xyongfeng.foodManagement.exception;


import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.xyongfeng.foodManagement.common.BaseResponse;
import com.xyongfeng.foodManagement.common.ErrorCode;
import com.xyongfeng.foodManagement.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }

    /**
     * 数据验证错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {

        List<ObjectError> allErrors = e.getAllErrors();
        ObjectError error = allErrors.get(0);
        log.info(error.getDefaultMessage());
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, error.getDefaultMessage());
    }


//    @ExceptionHandler(DataIntegrityViolationException.class)
//    public BaseResponse<?> invalidFormatExceptionHandler(DataIntegrityViolationException e) {
//        log.error("DataIntegrityViolationException", e);
//        return ResultUtils.error(ErrorCode.PARAMS_ERROR, "日期格式错误");
//    }

    @ExceptionHandler(UnauthorizedException.class)
    public BaseResponse<?> methodArgumentNotValidException(UnauthorizedException e) {

        log.info("UnauthorizedException", e);
        return ResultUtils.error(ErrorCode.NO_AUTH_ERROR);
    }
}
